package com.blank.site;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.blank.model.Company;

public class SunQiSite implements ISite {

	String defaulturl;

	public SunQiSite() {
		defaulturl = "http://jiangmen.11467.com/";
	}

	public void addListByUrl(String u) {

		try {
			InputStream is;
			is = Resources.getResourceAsStream("mybatis-config.xml");
			// 建立Session工厂
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
			// 获取Session
			SqlSession session = factory.openSession();
			Elements pages;
			String url = u;
			String defaulturl = "http://jiangmen.11467.com/";
			do {
				Document doc = Jsoup.parse(new URL(url).openStream(), "GBK", url);
				Elements elements = doc.select("#slist li h4 a:first-child");
				pages = doc.select(".pages a:contains(下页)");
				url = defaulturl + pages.attr("href");
				Iterator<Element> it = elements.iterator();

				while (it.hasNext()) {
					/*
					 * Document insidedoc =
					 * Jsoup.connect(it.next().attr("href")).data("query",
					 * "Java") .userAgent("Mozilla").cookie("auth",
					 * "token").timeout(3000).post();
					 */
					Element cp = it.next();
					Company company = new Company();
					company.setUrl(cp.attr("href"));
					company.setSource(defaulturl);
					company.setCompanyname(cp.attr("title"));
					session.insert(Company.class.getName() + ".add", company);

				}
			} while (pages.isEmpty() == false);
			session.commit();
			session.close();

		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public void run() {
		String defaulturl = "http://jiangmen.11467.com";

		Document doc;
		try {
			doc = Jsoup.parse(new URL(defaulturl).openStream(), "GBK", defaulturl);
			Elements elements = doc.select(".boxcontent").first().select("ul li a");
			for (Element element : elements) {
				this.addListByUrl(defaulturl + element.attr("href"));
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
